package com.tesis_2.UI;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.example.tesis_2.R;
import com.example.tesis_2.R.id;
import com.tesis_2.BL.BLLocales;
import com.tesis_2.BL.BLPlatos;
import com.tesis_2.BL.BLReservas;
import com.tesis_2.BL.BLRestaurants;
import com.tesis_2.MO.MOLocal;
import com.tesis_2.MO.MOPlato;
import com.tesis_2.MO.MOReserva;
import com.tesis_2.MO.MORestaurant;
import com.tesis_2.Utils.UTListViewUtility;

public class UIReservar extends Activity {

	MORestaurant objRestaurant;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reservar);
		Bundle b = getIntent().getExtras();
		int nRestId = b.getInt("RestId");
		
		objRestaurant = BLRestaurants.getRestById(nRestId);
		ArrayList<MOLocal> lsLocales = new ArrayList<MOLocal>();
		ArrayList<MOPlato> lsPLatos = new ArrayList<MOPlato>();
		
		try {
			lsLocales = BLLocales.getLocalsByRestId(nRestId);
			lsPLatos = BLPlatos.getPlatosByRestId(nRestId);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar minCal = new GregorianCalendar();
		long dtMili = System.currentTimeMillis() - 60000;
		
		((TextView) findViewById(R.id.txvRestaurantD_reservar)).setText(objRestaurant.getName());
		((TextView) findViewById(R.id.txvRestaurantD_reservar)).requestFocus();
		ArrayAdapter<MOLocal> spAdapter = new ArrayAdapter<MOLocal>(this, android.R.layout.simple_spinner_item, lsLocales);
		ArrayAdapter<MOPlato> multiListAdapter = new ArrayAdapter<MOPlato>
												(this,android.R.layout.simple_list_item_multiple_choice, lsPLatos);
		
		((Spinner) findViewById(R.id.spLocales_reservar)).setAdapter(spAdapter);
		((TimePicker) findViewById(R.id.tmpHora_reservar)).setCurrentHour(13);
		((TimePicker) findViewById(R.id.tmpHora_reservar)).setCurrentMinute(0);
		((TimePicker) findViewById(R.id.tmpHora_reservar)).setIs24HourView(true);
		((DatePicker) findViewById(R.id.dtpFecha_reservar)).setMinDate(dtMili);
		((TimePicker) findViewById(R.id.tmpHora_reservar)).setOnTimeChangedListener(mTimePickerListener);
		((ListView) findViewById(R.id.lsPlatos_reservar)).setAdapter(multiListAdapter);
		UTListViewUtility.setListViewHeightBasedOnChildren(((ListView) findViewById(R.id.lsPlatos_reservar)));
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_reservar, menu);
		return true;
	}
	
	private static final int TIME_PICKER_INTERVAL=30;
	private boolean mIgnoreEvent=false;

	private TimePicker.OnTimeChangedListener mTimePickerListener=new TimePicker.OnTimeChangedListener(){
	    public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute){
	        if (mIgnoreEvent)
	            return;
	        if (minute%TIME_PICKER_INTERVAL!=0){
	            int minuteFloor=minute-(minute%TIME_PICKER_INTERVAL);
	            minute=minuteFloor + (minute==minuteFloor+1 ? TIME_PICKER_INTERVAL : 0);
	            if (minute==60)
	                minute=0;
	            mIgnoreEvent=true;
	            timePicker.setCurrentMinute(minute);
	            mIgnoreEvent=false;
	        }

	    }
	};
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    
		Intent intent; 
		
		switch (item.getItemId()) 
	    {
	        case R.id.optGuardar_reservar:
	        	
			try {
				SaveReservation();
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        	//intent = new Intent(this, UILocales.class);
				//intent.putExtra("nRest", position);
				//startActivity(intent);
	        break;
	        
	        default: 
	        	
	        break;
	    }
	    return false;
	} 
	
	
	public void SaveReservation() throws ParseException, UnsupportedEncodingException {
		
		//obtener el restaurante
		//no es necesario, esta en el objeto de la clase
		
		//obtener el local: selecteditem del spinner
		
		MOLocal objlocal = (MOLocal) ((Spinner) findViewById(R.id.spLocales_reservar)).getSelectedItem();
		        
		//obtengo los restaurantes seleccionados
		
		ArrayList<MOPlato> lsselectedItemsPlatos = getSelectedPlatos();
      
		//obtener la hora
		
		int hour = ((TimePicker) findViewById(R.id.tmpHora_reservar)).getCurrentHour();
		int min =  ((TimePicker) findViewById(R.id.tmpHora_reservar)).getCurrentMinute();
		
		Date time = new Date(0,0,0,hour,min);
		//obtener la fecha
		
		int day = ((DatePicker) findViewById(R.id.dtpFecha_reservar)).getDayOfMonth();
		int month = ((DatePicker) findViewById(R.id.dtpFecha_reservar)).getMonth();
		int year = ((DatePicker) findViewById(R.id.dtpFecha_reservar)).getYear();
		
		@SuppressWarnings("deprecation")
		Date date = new Date(year,month,day);
		date.setYear(date.getYear()-1900);
		//obtengo la cantidad
		
		String cant = (((EditText) findViewById(R.id.txtCantidad_reservar)).getText().toString()) ;
		
		//creo el objeto
		
		MOReserva objReserva = new MOReserva();
		
		objReserva.setQty(Integer.parseInt(cant));
		objReserva.setQtytable(1); //toDo
		objReserva.setRdate(date);
		objReserva.setRtime(time);
		objReserva.setStatus(1); 
		objReserva.setTable_id(1); //toDo
		objReserva.setRestaurant_id(objRestaurant.getId());
		objReserva.setRestaurant_name("");
		objReserva.setLocal_id(objlocal.getId());
		objReserva.setLocal_name("");
		
		//concateno los id de los platos a mandar.
		
		String IdPlatosSelected = "";
		
		for( MOPlato p : getSelectedPlatos())
		{
			IdPlatosSelected = IdPlatosSelected + p.getId() + "-";
		}
		if ( IdPlatosSelected.equals("") ) {IdPlatosSelected = "%20";}
		MOReserva objR2 = BLReservas.generateReserva(objReserva,IdPlatosSelected);
        finish();
    }
	
	public ArrayList<MOPlato> getSelectedPlatos()
	{
		SparseBooleanArray lsChecked = ((ListView) findViewById(R.id.lsPlatos_reservar)).getCheckedItemPositions();
        ArrayAdapter<MOPlato> lsPlatosAdapter;
        ArrayList<MOPlato> lsselectedItemsPlatos = new ArrayList<MOPlato>();
        
        lsPlatosAdapter = (ArrayAdapter<MOPlato>) ((ListView) findViewById(R.id.lsPlatos_reservar)).getAdapter();
   
        for (int i = 0; i < lsChecked.size(); i++) {
            // Item position in adapter
            int position = lsChecked.keyAt(i);
            // Add sport if it is checked i.e.) == TRUE!
            if (lsChecked.valueAt(i))
            	lsselectedItemsPlatos.add(lsPlatosAdapter.getItem(position));
        }
        
        return lsselectedItemsPlatos;
	}



}
